<?php

class GroupServiceTest extends PHPUnit_Framework_TestCase
{
    private $subject;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp ()
    {
        parent::setUp();
        $this->subject = RedCross_Factory::getService('Core_Service_Group');
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown ()
    {
        parent::tearDown();
        unset($this->subject);
    }

    public function testImplementsRedCrossServiceServiceInterface()
    {
        $this->assertTrue($this->subject instanceof RedCross_Service_ServiceInterface);
    }

    public function testExtendsRedCrossServiceServiceAbstract()
    {
        $this->assertTrue($this->subject instanceof RedCross_Service_ServiceAbstract);
    }

    public function testCanFetchGroupsById()
    {
        $group = $this->subject->fetchById(1);
        $this->assertSame('1', $group->id);
        $this->assertSame('Medlem', $group->name);
    }

    public function testCanFetchAllGroups()
    {
        $groups = $this->subject->fetchAll();
        $this->assertSame(3, count($groups));
    }

    public function testCanEditGroups()
    {
        $group = $this->subject->fetchById(1);
        $this->assertSame('Medlem', $group->name);

        $data = array('name' => 'Test');
        $this->subject->edit($group, $data);
        $group2 = $this->subject->fetchById(1);
        $this->assertSame('Test', $group->name);
        $group->name = 'Medlem';
        $group->save();
    }

    public function testAddingAndRemovingUsersFromGroupsWorks()
    {
        $group = $this->subject->fetchById(1);
        $this->assertSame(0, count($group->Users));
        $user = RedCross_Factory::getService('Core_Service_User');
        $user = $user->fetch(1);
        // Add user
        $this->subject->addUser(1, 1);
        $group = $this->subject->fetchById(1);
        $this->assertSame(1, count($group->Users));
        // Remove user
        $this->subject->removeUser(1, 1);
        $group = $this->subject->fetchById(1);
        $this->assertSame(0, count($group->Users));
    }

    public function testFetchingUsersNotInTheGroup()
    {
        $group = $this->subject->fetchById(1);
        $this->assertSame(0, count($group->Users));

        $this->subject->addUser(1, 1);

        $users = $this->subject->fetchUsersNotInGroup(1);

        $allUsers = $this->subject->fetchAll();

        $this->assertSame(count($allUsers) - 1, count($users));

        $this->subject->removeUser(1, 1);
    }
}

